<template>
  <div class="user-center-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="个人中心"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <!-- 用户基本信息卡片 -->
    <div class="user-profile-card">
      <div class="user-info-section">
        <div class="user-avatar">
          <van-image
            round
            width="80"
            height="80"
            :src="userInfo?.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'"
            fit="cover"
          />
        </div>
        <div class="user-info">
          <div class="user-name">
            {{ userInfo?.nickname || userInfo?.username || "用户" }}
          </div>
          <div class="user-level">
            <van-tag type="primary" size="medium">{{
              userInfo?.role === "admin" ? "管理员" : "普通用户"
            }}</van-tag>
          </div>
          <div class="user-signature">
            {{ userInfo?.email || "未设置邮箱" }}
          </div>
        </div>
        <div class="edit-profile" @click="isEditing = true">
          <van-button size="small" plain hairline type="primary"
            >编辑资料</van-button
          >
        </div>
      </div>

      <div class="user-data-section">
        <div class="data-item">
          <div class="data-value">{{ historyList.length || 0 }}</div>
          <div class="data-label">浏览</div>
        </div>
        <div class="data-item">
          <div class="data-value">{{ recipeList.length || 0 }}</div>
          <div class="data-label">收藏</div>
        </div>
      </div>
    </div>

    <!-- 功能入口 简化版 -->
    <div class="features-section">
      <div class="section-header">
        <div class="section-title">我的服务</div>
      </div>
      <div class="features-grid simplified">
        <div class="feature-item" @click="$router.push('/history')">
          <van-icon name="clock-o" />
          <span>浏览历史</span>
        </div>
        <div class="feature-item" @click="$router.push('/collection')">
          <van-icon name="star-o" />
          <span>我的收藏</span>
        </div>
        <div class="feature-item" @click="handlePasswordClick">
          <van-icon name="lock" />
          <span>修改密码</span>
        </div>
      </div>
    </div>

    <!-- 浏览历史部分 -->
    <div class="history-section">
      <div class="section-header">
        <div class="section-title">最近浏览</div>
        <div class="section-more" @click="$router.push('/history')">
          查看更多 <van-icon name="arrow" />
        </div>
      </div>
      <div class="history-list">
        <van-skeleton
          title
          :row="3"
          :loading="historyLoading"
          v-for="i in 3"
          :key="i"
          v-if="historyList.length === 0 && historyLoading"
        />
        <div
          v-for="item in historyList.slice(0, 3)"
          :key="item.id"
          class="history-item"
          @click="navigateToDetail(item)"
        >
          <van-image
            width="80"
            height="80"
            :src="item.image || 'https://img.yzcdn.cn/vant/cat.jpeg'"
            fit="cover"
          />
          <div class="history-info">
            <div class="history-name">{{ item.name }}</div>
            <div class="history-meta">
              <span class="history-type">{{ getItemTypeName(item.type) }}</span>
              <span class="history-time">{{ formatTime(item.viewTime) }}</span>
            </div>
          </div>
        </div>
        <div
          class="empty-tip"
          v-if="historyList.length === 0 && !historyLoading"
        >
          暂无浏览记录
        </div>
      </div>
    </div>

    <!-- 收藏列表 -->
    <div class="collection-section">
      <div class="section-header">
        <div class="section-title">我的收藏</div>
        <div class="section-more" @click="$router.push('/collection')">
          查看更多 <van-icon name="arrow" />
        </div>
      </div>
      <div class="collection-list">
        <van-skeleton
          title
          :row="3"
          :loading="favoritesLoading"
          v-for="i in 3"
          :key="i"
          v-if="recipeList.length === 0 && favoritesLoading"
        />
        <div
          v-for="item in recipeList.slice(0, 3)"
          :key="item.id"
          class="collection-item"
          @click="$router.push(`/recipe/${item.id}`)"
        >
          <van-image
            width="80"
            height="80"
            :src="item.image || 'https://img.yzcdn.cn/vant/cat.jpeg'"
            fit="cover"
          />
          <div class="collection-info">
            <div class="collection-name">{{ item.name }}</div>
            <div class="collection-desc">{{ item.desc }}</div>
          </div>
        </div>
        <div
          class="empty-tip"
          v-if="recipeList.length === 0 && !favoritesLoading"
        >
          暂无收藏
        </div>
      </div>
    </div>

    <!-- 编辑个人资料 -->
    <van-popup
      v-model="isEditing"
      position="bottom"
      :style="{ height: '70%' }"
      round
    >
      <div class="edit-profile-popup">
        <div class="popup-header">
          <div class="popup-title">编辑个人资料</div>
          <van-icon name="cross" @click="isEditing = false" />
        </div>

        <van-form @submit="handleUpdateProfile">
          <van-cell-group inset>
            <van-field v-model="profileForm.username" label="用户名" readonly />
            <van-field
              v-model="profileForm.nickname"
              label="昵称"
              placeholder="请输入昵称"
              :rules="[{ required: true, message: '请输入昵称' }]"
            />
            <van-field
              v-model="profileForm.email"
              label="邮箱"
              placeholder="请输入邮箱"
              :rules="[{ required: true, message: '请输入邮箱' }]"
            />
            <van-field name="gender" label="性别">
              <template #input>
                <van-radio-group
                  v-model="profileForm.gender"
                  direction="horizontal"
                >
                  <van-radio :name="1">男</van-radio>
                  <van-radio :name="2">女</van-radio>
                  <van-radio :name="0">不公开</van-radio>
                </van-radio-group>
              </template>
            </van-field>
          </van-cell-group>

          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit">
              保存修改
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>

    <!-- 修改密码表单 -->
    <van-popup
      v-model="showPasswordPopup"
      position="bottom"
      :style="{ height: '60%' }"
      round
    >
      <div class="edit-profile-popup">
        <div class="popup-header">
          <div class="popup-title">修改密码</div>
          <van-icon name="cross" @click="showPasswordPopup = false" />
        </div>

        <van-form @submit="handleUpdatePassword">
          <van-cell-group inset>
            <van-field
              v-model="passwordForm.oldPassword"
              type="password"
              label="原密码"
              placeholder="请输入原密码"
              :rules="[{ required: true, message: '请输入原密码' }]"
            />
            <van-field
              v-model="passwordForm.newPassword"
              type="password"
              label="新密码"
              placeholder="请输入新密码"
              :rules="[{ required: true, message: '请输入新密码' }]"
            />
            <van-field
              v-model="passwordForm.confirmPassword"
              type="password"
              label="确认密码"
              placeholder="请再次输入新密码"
              :rules="[
                { required: true, message: '请再次输入新密码' },
                {
                  validator: validateConfirmPassword,
                  message: '两次输入的密码不一致',
                },
              ]"
            />
          </van-cell-group>

          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit">
              确认修改
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { showToast, showSuccessToast, showConfirmDialog } from "vant";
import { useUserStore } from "../../stores/userStore";
import {
  getUserInfo as getAuthUserInfo,
  setUserInfo,
  logout,
} from "../../utils/auth";
import {
  getBrowseHistoryPage,
  deleteBrowseHistory,
  clearBrowseHistory,
} from "../../api/user";

const router = useRouter();
const userStore = useUserStore();

// 用户信息相关变量
const userInfo = computed(() => {
  return (
    userStore.userInfo || JSON.parse(localStorage.getItem("userInfo") || "{}")
  );
});
const profileLoading = ref(false);
const isEditing = ref(false);
const showPasswordPopup = ref(false);

// 用户表单数据
const userForm = reactive({
  nickname: "",
  username: "",
  email: "",
  gender: 0,
  avatar: "",
});

// 个人信息编辑表单
const profileForm = reactive({
  username: "",
  nickname: "",
  email: "",
  gender: 0,
});

// 密码表单
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 浏览记录相关变量
const historyLoading = ref(true);
const historyList = ref([]);
const historyCurrentPage = ref(1);
const historyPageSize = ref(10);

// 收藏相关变量
const favoritesLoading = ref(false);
const recipeList = ref([]);
const recipePage = ref(1);
const favoritesPageSize = ref(8);

// 获取用户ID
const userId = computed(() => userStore.userId);

// 验证确认密码
const validateConfirmPassword = (val) => {
  return val === passwordForm.newPassword;
};

// ==================== 个人信息相关函数 ====================

// 模拟API函数 - 获取用户信息
const getUserInfo = async (userId) => {
  // 这里替换为实际的API调用
  console.log(`获取用户${userId}的详细信息`);

  // 模拟数据 - 实际应从本地存储或API获取
  const localUserInfo = getAuthUserInfo();

  return {
    code: 200,
    data: {
      id: localUserInfo?.id || 1,
      username: localUserInfo?.username || "user123",
      nickname: localUserInfo?.nickname || "用户昵称",
      email: localUserInfo?.email || "user@example.com",
      gender: localUserInfo?.gender !== undefined ? localUserInfo.gender : 0,
      avatar: localUserInfo?.avatar || "https://img.yzcdn.cn/vant/cat.jpeg",
    },
  };
};

// 模拟API函数 - 更新用户信息
const updateUserInfo = async (userId, data) => {
  console.log(`更新用户${userId}的信息`, data);
  return {
    code: 200,
    message: "更新成功",
    data: {
      ...data,
      id: userId,
    },
  };
};

// 模拟API函数 - 修改密码
const changePassword = async (userId, data) => {
  console.log(`修改用户${userId}的密码`, data);
  return { code: 200, message: "密码修改成功" };
};

// 加载用户信息
const loadUserInfo = async () => {
  try {
    profileLoading.value = true;
    const res = await getUserInfo(userId.value);

    if (res.code === 200 && res.data) {
      // 设置表单初始值
      Object.keys(userForm).forEach((key) => {
        if (res.data[key] !== undefined) {
          userForm[key] = res.data[key];
        }
      });

      // 设置个人信息编辑表单
      profileForm.username = res.data.username || "";
      profileForm.nickname = res.data.nickname || "";
      profileForm.email = res.data.email || "";
      profileForm.gender = res.data.gender || 0;
    } else {
      showToast("获取用户信息失败");
    }
  } catch (error) {
    console.error("加载用户信息失败", error);
    showToast("获取用户信息失败");
  } finally {
    profileLoading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    profileLoading.value = true;
    const res = await updateUserInfo(userId.value, userForm);

    if (res.code === 200) {
      showSuccessToast("保存成功");

      // 更新本地存储的用户信息
      const updatedUserInfo = {
        ...getAuthUserInfo(),
        ...res.data,
      };
      setUserInfo(updatedUserInfo);

      // 更新用户store
      userStore.userInfo = updatedUserInfo;
    } else {
      showToast("保存失败");
    }
  } catch (error) {
    console.error("更新用户信息失败", error);
    showToast("保存失败");
  } finally {
    profileLoading.value = false;
  }
};

// 修改密码
const handleChangePassword = async () => {
  try {
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      showToast("两次输入的密码不一致");
      return;
    }

    const res = await changePassword(userId.value, {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
    });

    if (res.code === 200) {
      showSuccessToast("密码修改成功");

      // 清空表单
      passwordForm.oldPassword = "";
      passwordForm.newPassword = "";
      passwordForm.confirmPassword = "";
      showPasswordPopup.value = false;
    } else {
      showToast("密码修改失败");
    }
  } catch (error) {
    console.error("修改密码失败", error);
    showToast("密码修改失败");
  }
};

// ==================== 浏览记录相关函数 ====================

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return "";
  const date = new Date(timestamp);
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  return `${hours}:${minutes}`;
};

// 获取项目类型名称
const getItemTypeName = (type) => {
  switch (type) {
    case "recipe":
      return "食谱";
    case "food":
      return "食材";
    default:
      return "未知类型";
  }
};

// 加载浏览记录
const loadBrowseHistory = async () => {
  try {
    historyLoading.value = true;
    const res = await getBrowseHistoryPage(
      userId.value,
      historyCurrentPage.value,
      historyPageSize.value
    );

    if (res.code === 200 && res.data) {
      if (res.data.records && res.data.records.length > 0) {
        historyList.value = res.data.records;
      }
    } else {
      showToast("获取浏览记录失败");
    }
  } catch (error) {
    console.error("加载浏览记录失败", error);
    showToast("获取浏览记录失败");
  } finally {
    historyLoading.value = false;
  }
};

// ==================== 收藏相关函数 ====================

// 模拟API函数 - 获取收藏食谱
const getFavoriteRecipes = async (userId, page, size) => {
  console.log(`获取用户${userId}的收藏食谱, 页码:${page}, 大小:${size}`);

  // 模拟数据
  return {
    code: 200,
    data: {
      records: [
        {
          id: 1,
          name: "健康沙拉",
          desc: "多种蔬菜搭配，营养丰富",
          image: "https://img.yzcdn.cn/vant/cat.jpeg",
        },
        {
          id: 2,
          name: "牛油果三明治",
          desc: "富含不饱和脂肪酸",
          image: "https://img.yzcdn.cn/vant/cat.jpeg",
        },
        {
          id: 3,
          name: "蒸鲈鱼",
          desc: "低脂高蛋白",
          image: "https://img.yzcdn.cn/vant/cat.jpeg",
        },
      ],
      total: 3,
      size: size,
      current: page,
    },
  };
};

// 加载收藏的食谱
const loadFavoriteRecipes = async () => {
  try {
    favoritesLoading.value = true;
    const res = await getFavoriteRecipes(
      userId.value,
      recipePage.value,
      favoritesPageSize.value
    );

    if (res.code === 200 && res.data) {
      if (res.data.records && res.data.records.length > 0) {
        recipeList.value = res.data.records;
      }
    } else {
      showToast("获取收藏食谱失败");
    }
  } catch (error) {
    console.error("加载收藏食谱失败", error);
    showToast("获取收藏食谱失败");
  } finally {
    favoritesLoading.value = false;
  }
};

// ==================== 通用函数 ====================

// 导航到详情页
const navigateToDetail = (item) => {
  if (!item.type || !item.targetId) return;

  switch (item.type) {
    case "recipe":
      router.push(`/recipe/${item.targetId}`);
      break;
    case "food":
      router.push(`/food/${item.targetId}`);
      break;
    default:
      break;
  }
};

// 密码弹窗
const handlePasswordClick = () => {
  showPasswordPopup.value = true;
};

// 更新资料
const handleUpdateProfile = () => {
  userForm.nickname = profileForm.nickname;
  userForm.email = profileForm.email;
  userForm.gender = profileForm.gender;

  handleSubmit();
  isEditing.value = false;
  showSuccessToast("个人资料更新成功");
};

// 更新密码
const handleUpdatePassword = () => {
  handleChangePassword();
};

// 页面加载时初始化
onMounted(() => {
  loadUserInfo();
  loadBrowseHistory();
  loadFavoriteRecipes();
});
</script>

<style scoped>
.user-center-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 60px;
  padding-top: 46px;
}

.user-profile-card {
  background-color: #ff6000;
  color: #fff;
  padding: 20px 16px;
  margin-bottom: 12px;
}

.user-info-section {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  background-color: #fff;
}

.user-info {
  flex: 1;
  margin-left: 16px;
}

.user-name {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 4px;
}

.user-level {
  margin-bottom: 4px;
}

.user-signature {
  font-size: 12px;
  opacity: 0.8;
}

.edit-profile .van-button {
  color: #fff;
  border-color: #fff;
}

.user-data-section {
  display: flex;
  justify-content: space-around;
  text-align: center;
}

.data-value {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 4px;
}

.data-label {
  font-size: 12px;
  opacity: 0.8;
}

.features-section,
.history-section,
.collection-section {
  background-color: #fff;
  margin-bottom: 12px;
  padding: 16px;
  border-radius: 8px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
}

.section-more {
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.features-grid.simplified {
  padding: 10px 0;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
}

.feature-item .van-icon {
  font-size: 24px;
  margin-bottom: 4px;
  color: #ff6000;
}

.history-list,
.collection-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item,
.collection-item {
  display: flex;
  background-color: #f8f8f8;
  border-radius: 8px;
  padding: 8px;
}

.history-info,
.collection-info {
  flex: 1;
  margin-left: 12px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.history-name,
.collection-name {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 4px;
}

.history-meta,
.collection-desc {
  font-size: 12px;
  color: #999;
}

.history-type {
  background-color: #e8f3ff;
  color: #1989fa;
  padding: 2px 6px;
  border-radius: 4px;
  margin-right: 8px;
}

.history-time {
  color: #999;
}

.empty-tip {
  text-align: center;
  padding: 20px 0;
  color: #999;
  font-size: 14px;
}

.edit-profile-popup {
  padding: 16px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.popup-title {
  font-size: 18px;
  font-weight: bold;
}

/* 适配平板和PC */
@media (min-width: 768px) {
  .user-profile-card {
    border-radius: 8px;
    margin: 16px;
  }

  .features-section,
  .history-section,
  .collection-section {
    margin: 0 16px 16px;
  }
}
</style>
